﻿using GMS.NET.Consts;
using MQTTnet;
using MQTTnet.Server;

namespace GMS.NET.Application.Service.System.Extensions
{
    public static class MqttServerExtensions
    {

        public static void PublishByHub(this MqttServer mqttServer, string topic, string payload)
        {
            if (topic == null)
                throw new ArgumentNullException(nameof(topic));
            mqttServer.PublishByHub(new MqttApplicationMessageBuilder()
                .WithTopic(topic)
                .WithPayload(payload)
                .Build());
        }

        public static void PublishByHub(this MqttServer mqttServer, MqttApplicationMessage mqttApplicationMessage)
        {
            if (mqttServer == null)
                throw new ArgumentNullException(nameof(mqttServer));
            if (mqttApplicationMessage == null)
                throw new ArgumentNullException(nameof(mqttApplicationMessage));


            mqttServer.InjectApplicationMessage(new InjectedMqttApplicationMessage(mqttApplicationMessage)
            {
                SenderClientId = MqttNetConst.IotHubMqttClientId
            });
        }


        public static async Task PublishByHubAsync(this MqttServer mqttServer, string topic, string payload)
        {
            if (topic == null)
                throw new ArgumentNullException(nameof(topic));
            await mqttServer.PublishByHubAsync(new MqttApplicationMessageBuilder()
                .WithTopic(topic)
                .WithPayload(payload)
                .Build());
        }

        public static async Task PublishByHubAsync(this MqttServer mqttServer, MqttApplicationMessage mqttApplicationMessage)
        {
            if (mqttServer == null)
                throw new ArgumentNullException(nameof(mqttServer));
            if (mqttApplicationMessage == null)
                throw new ArgumentNullException(nameof(mqttApplicationMessage));
            await mqttServer.InjectApplicationMessage(new InjectedMqttApplicationMessage(mqttApplicationMessage)
            {
                SenderClientId = MqttNetConst.IotHubMqttClientId
            });

        }
    }
}
